package com.cqc.customslidmenu01;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by a on 2018/3/20.
 * 侧滑菜单
 */

public class SlideView4 extends ViewGroup {

    private int menuViewWidth;
    private View menuView;
    private View contentView;
    private int downX;
    private int moveX;

    public SlideView4(Context context) {
        this(context, null);
    }

    public SlideView4(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlideView4(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        menuView = getChildAt(0);
        menuViewWidth = menuView.getLayoutParams().width;
        menuView.measure(menuViewWidth, heightMeasureSpec);

        contentView = getChildAt(1);
        contentView.measure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        menuView.layout(-menuViewWidth, t, 0, b);
        contentView.layout(l, t, r, b);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                moveX = (int) event.getX();
                int instance = downX - moveX;
                int scrollX = getScrollX() + instance;
                if (scrollX < -menuViewWidth) {
                    //注意不是menuView.scrollTo(-menuViewWidth, 0);
                    scrollTo(-menuViewWidth, 0);
                } else if (scrollX > 0) {
                    scrollTo(0, 0);
                } else {
                    scrollBy(instance, 0);
                }
                downX = moveX;
                break;

            case MotionEvent.ACTION_UP:
                break;
        }

        return true;
    }
}
